package com.orange.lswidget.widgets.event.manager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.CallLog.Calls;
import android.text.TextUtils;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.RemoteViews;

import com.orange.lswidget.R;
import com.orange.lswidget.widgets.event.dao.UnreadSMSDao;
import com.orange.notificationsummary.event.MessageInfo;
import com.orange.notificationsummary.event.db.NotificationDBHelper;
import com.orange.notificationsummary.event.pil.defaultimpl.BaseEvent;
import com.orange.notificationsummary.utils.Constants;
import com.orange.notificationsummary.utils.Constants.EventType;
import com.orange.notificationsummary.utils.EventLSWidgetUtils;
import com.orange.util.LSEventUtils;
import com.orange.util.LSServiceUtils;
import com.orange.util.LogHelper;
import com.orange.util.UnreadSMSUtils;

public class UnreadMsgManager extends EventManager implements EventType {
	private static final String			TAG					= "UnreadMsgManager";

	private static final String			THREAD_CONTENT_URI	= "content://mms-sms/conversations/";

	private static UnreadMsgManager		sUnreadMsgManager;
	private static Object				sObject				= new Object();
	private List<Map<String, String>>	mResultList;
	private UnreadSMSDao				mMsgDao;

	private int							mSMSCount;
	private String						mSmsBody;

	private int							mMMSCount;
	private boolean						mIsHaveMMSImage;
	private String						mMmsSubject;
	private String						mMmsBody;
	private int							mAttImageCount;
	private int							mAttGenericCount;
	private String						mID;
	private String						mThreadId;

	private UnreadMsgManager(Context context) {
		super(context);
		mMsgDao = new UnreadSMSDao(context);
		mResultList = new ArrayList<Map<String, String>>();

		mBasicIconResId = R.drawable.event_sms_icon;
		mDetailedIconResId = R.drawable.event_sms_icon_small;
		mBasicTypeString = context.getResources().getString(
				R.string.new_message);
		mDetailedTypeString = context.getResources()
				.getString(R.string.message);

		mType = UNMSG_UPDATE;
	}

	public static UnreadMsgManager getInstance(Context context) {
		if (sUnreadMsgManager == null) {
			synchronized (sObject) {
				if (sUnreadMsgManager == null) {
					sUnreadMsgManager = new UnreadMsgManager(context);
				}
			}
		}
		return sUnreadMsgManager;
	}

	public List<Map<String, String>> queryAllUnreadMsgToList() {
		if (!mResultList.isEmpty()) {
			mResultList.clear();
		}
		mResultList = mMsgDao.queryAllUnreadMsgToList();

		setCount();
		return mResultList;
	}

	@Override
	protected void setCount() {
		List<MessageInfo> mmsList = mMsgDao.getUnreadMmsInfo();
		List<MessageInfo> smsList = mMsgDao.getUnreadSmsInfo();

		if (mmsList != null) {
			// mmsList = mMsgDao.isNotShowMMS(mmsList);
			mMMSCount = mmsList.size();
		}

		if (smsList != null) {
			mSMSCount = smsList.size();
		}

		mCount = mMMSCount + mSMSCount;
		LogHelper.e(TAG, "setCount. mCount: " + mCount + " ,mMMSCount: "
				+ mMMSCount + " ,mSMSCount: " + mSMSCount);
	}

	@Override
	public void updateSummaryInfo() {
		if (null == mResultList || mResultList.isEmpty()) {
			mCount = 0;
			mLastEventTime = 0;
		} else {
			if (mCount > 1) {
				mBasicTypeString = mContext.getResources().getString(
						R.string.new_messages);
			} else {
				mBasicTypeString = mContext.getResources().getString(
						R.string.new_message);
			}

			List<String> numberList = UnreadSMSUtils.getNumbersByResult(
					mContext, mResultList);
			LSEventUtils.updateNamesByNumbers(mContext, numberList, mNames);

			mLastEventTime = Long.parseLong(mResultList.get(0).get(Calls.DATE));
			mTime = EventLSWidgetUtils.dateFormat(mContext, mLastEventTime);

			// Map<String, String> messageMap = getLastMessage(mResultList);
			// mID = messageMap.get(_ID);
			mThreadId = mResultList.get(0).get(_ID);

			LogHelper.e(TAG, "updateSummaryInfo. mCount: " + mCount
					+ " ,mMMSCount: " + mMMSCount + " ,mSMSCount: " + mSMSCount
					+ " ,mLastEventTime: " + mLastEventTime + " ,mTime: "
					+ mTime);
		}
	}

	@Override
	public void updateDetailedInfo() {
		List<BaseEvent> unreadMsg = mMsgDao.getAllUnreadMessageEvent();

		if (unreadMsg != null && !unreadMsg.isEmpty()) {
			LogHelper.v(TAG, "updateDetailedInfo. unreadMsg.size(): "
					+ unreadMsg.size());
			mID = String.valueOf(unreadMsg.get(0).id);
			mThreadId = String.valueOf(unreadMsg.get(0).threadId);

			mSmsBody = unreadMsg.get(0).event_sms_content;
			mMmsSubject = unreadMsg.get(0).event_mms_subject;
			mMmsBody = unreadMsg.get(0).event_mms_content;

			mIsVip = unreadMsg.get(0).isVip;
			mNumberCountByContact = unreadMsg.get(0).phoneNumberCount;

			mLastEventTime = unreadMsg.get(0).event_date;
			mTime = EventLSWidgetUtils.dateFormat(mContext, mLastEventTime);

			List<String> numberList = UnreadSMSUtils.getNumbersByResult(
					mContext, mResultList);
			LSEventUtils.updateNamesByNumbers(mContext, numberList, mNames);

			if (!EventLSWidgetUtils.getEventPreviewSetting(mContext)) {
				mNumberLabel = unreadMsg.get(0).evnet_number_type;
			}
			if (mNumberCountByContact > 1 && !TextUtils.isEmpty(mNumberLabel)) {
				mFrom = LSEventUtils.getNameString(mContext, mNames,
						mNumberLabel);
			} else {
				mFrom = LSEventUtils.getNameString(mContext, mNames);
			}

			LogHelper.i(TAG, "updateDetailedInfo. mNumberCountByContact: "
					+ mNumberCountByContact + " ,mNumberLabel: " + mNumberLabel
					+ " ,mNames: " + mNames + " ,mIsVip: " + mIsVip);
			// Map<String, String> messageMap = getLastMessage(mResultList);

			// Bitmap contactPhoto =
			// EventLSWidgetUtils.getContactPhoto(messageMap
			// .get(RECIPIENT_IDS), true, mContext.getContentResolver());

			// Bitmap contactPhoto=
			// EventLSWidgetUtils.getContactPhoto(recipient_ids,
			// true, mContext.getContentResolver());
			// Bitmap contactPhoto = unreadMsg.get(0).contacts_image;

			String recipient_ids = unreadMsg.get(0).threads_recipient;

			Bitmap contactPhoto = null;
			String contact_id = unreadMsg.get(0).contacts_id;

			if (!TextUtils.isEmpty(contact_id)) {
				contactPhoto = NotificationDBHelper.getContactsPhoto(mContext,
						contact_id);
			}

			LogHelper.d(TAG, "updateDetailedInfo. mID: " + mID + ", mTime: "
					+ mTime + ", mFrom: " + mFrom + " , mSmsBody: " + mSmsBody
					+ " , mMmsBody: " + mMmsBody + " , mMmsSubject: "
					+ mMmsSubject + " ,recipient_ids: " + recipient_ids
					+ " ,contacts_id: " + contact_id);

			if (mCount == 1 && mSMSCount == 1) {
				updateSMSDetailedInfo(contactPhoto);
			}

			if (mCount == 1 && mMMSCount == 1) {
				updateMMSDetailedInfo(contactPhoto);
			}
		}
	}

	private void updateSMSDetailedInfo(Bitmap contactPhoto) {
		mBitmap = contactPhoto;
		mMmsBody = null;
		mIsHaveMMSImage = false;
	}

	private void updateMMSDetailedInfo(Bitmap contactPhoto) {
		Map<String, Integer> attMap = mMsgDao
				.getAttachmentCountInMMSDetailed(mID);

		if (attMap != null && !attMap.isEmpty()) {
			LogHelper.i(TAG, "updateMMSDetailedInfo. attMap: " + attMap);
			mAttImageCount = attMap.get(Constants.KEY_MMS_ATTACHMENT_IMAGE);
			mAttGenericCount = attMap.get(Constants.KEY_MMS_ATTACHMENT_GENERIC);
		} else {
			mAttImageCount = 0;
			mAttGenericCount = 0;
		}

		int attCount = mAttImageCount + mAttGenericCount;
		// add by gaoge 2011-08-22,for fix bug 0013226
		// if (attCount > 1) {
		// mBitmap = contactPhoto;
		// }
		if (mAttImageCount <= 0) {
			mBitmap = contactPhoto;
		} else {
			mBitmap = mMsgDao.getMmsPhotobyMmsId(mID);
			mIsHaveMMSImage = true;

			if (mBitmap == null) {
				mBitmap = contactPhoto;
				mIsHaveMMSImage = false;
			}
		}

		String text = mMsgDao.getMmsTextContent(mID);
		if (text != null && !TextUtils.isEmpty(text.trim())) {
			mMmsBody = text.trim();
		}
	}

	@Override
	public RemoteViews getDetailedView(RemoteViews remoteViews) {
		remoteViews.setViewVisibility(R.id.basic, View.GONE);
		remoteViews.setViewVisibility(R.id.detailed, View.VISIBLE);

		remoteViews.setImageViewResource(R.id.event_detailed_icon,
				mDetailedIconResId);
		remoteViews.setTextViewText(R.id.event_detailed_type,
				mDetailedTypeString);
		remoteViews.setTextViewText(R.id.event_detailed_time, mTime);
		remoteViews.setTextViewText(R.id.event_detailed_number, mFrom);

		int attCount = getMMSAttCount();

		if (attCount == 0) {
			updateDeatailedViewNoAtt(remoteViews);
		} else if (attCount == 1) {
			updateDetailedViewSingleAtt(remoteViews);
		} else if (attCount > 1) {
			updateDetailedViewMultiAtt(remoteViews);
		}

		return remoteViews;
	}

	private int getMMSAttCount() {
		int attCount = 0;
		if (mMMSCount == 1) {
			attCount = mAttImageCount + mAttGenericCount;
		} else if (mSMSCount == 1) {
			attCount = 0;
		}

		return attCount;
	}

	public void startUnreadMessageActivity() throws Exception {
		Intent intent = new Intent();
		boolean isNtfcExists = EventLSWidgetUtils.isPackageExist(mContext,
				Constants.PKG_NOTIFICATION_SUMMARY);
		boolean isNtfcEnabled = EventLSWidgetUtils
				.isNotificationScreenEnabled(mContext);

		if (!isNtfcExists) {
			startComposeMessageActivity(intent, mThreadId);
		} else {
			if (!isNtfcEnabled) {
				startComposeMessageActivity(intent, mThreadId);
			} else {
				if (UnreadSMSUtils.isUnreadSMSFromSameSender(mContext,
						mResultList)) {
					// String unreadMessageId = getID();
					startComposeMessageActivity(intent, mThreadId);
				} else {
					startConversationListActivity(intent);
				}
			}
		}
	}

	private void startConversationListActivity(Intent intent) {
		intent.setAction(Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		ComponentName component = new ComponentName("com.android.mms",
				"com.android.mms.ui.ConversationList");
		intent.setComponent(component);
		LSServiceUtils.startActivity(mContext, intent);
	}

	private void startComposeMessageActivity(Intent intent,
			String unreadMessageId) {
		String unMsgId = THREAD_CONTENT_URI + unreadMessageId;
		LogHelper.d(TAG, "startComposeMessageActivity. uri: " + unMsgId);
		intent.setAction(Intent.ACTION_VIEW);
		intent.setData(Uri.parse(unMsgId));
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		LSServiceUtils.startActivity(mContext, intent);
	}

	private void updateDeatailedViewNoAtt(RemoteViews remoteViews) {
		remoteViews.setViewVisibility(R.id.mms_attachement_icon, View.GONE);

		remoteViews.setViewVisibility(R.id.mms_image_framelayout, View.GONE);
		remoteViews.setViewVisibility(R.id.contact_image_framelayout,
				View.VISIBLE);

		// image
		if (null == mBitmap) {
			remoteViews.setImageViewResource(R.id.contact_detailed_image,
					R.drawable.event_nobody);
		} else {
			remoteViews
					.setImageViewBitmap(R.id.contact_detailed_image, mBitmap);
		}

		if (mIsVip) {
			remoteViews.setViewVisibility(R.id.contact_vip_image, View.VISIBLE);
		} else {
			remoteViews.setViewVisibility(R.id.contact_vip_image,
					View.INVISIBLE);
		}

		String mmsURL = mMsgDao.getMMSContentLocationUrl(mID);
		LogHelper.v(TAG, "updateDeatailedViewNoAtt. mID: " + mID + " ,mmsURL: "
				+ mmsURL);
		if (URLUtil.isNetworkUrl(mmsURL)) {
			remoteViews.setViewVisibility(R.id.mms_attachement_icon,
					View.VISIBLE);
		} else {
			remoteViews.setViewVisibility(R.id.mms_attachement_icon, View.GONE);
		}

		LogHelper.i(TAG, "updateDeatailedViewNoAtt. mMmsSubject: "
				+ mMmsSubject + " , mMmsBody: " + mMmsBody + " , mSmsBody: "
				+ mSmsBody);
		if(null != mSmsBody){
			LogHelper.d(TAG, "$$$$$$$$$$$$$$ mSmsBody.equals(\" \" ): " + mSmsBody.equals(" "));
		}
		if (!TextUtils.isEmpty(mMmsSubject) && !TextUtils.isEmpty(mMmsBody)
				&& TextUtils.isEmpty(mSmsBody)) { // mms
			remoteViews.setViewVisibility(R.id.event_sms_detailed_description,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_subject,
					mMmsSubject);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_description,
					mMmsBody);
		} else if (!TextUtils.isEmpty(mMmsSubject)
				&& TextUtils.isEmpty(mMmsBody) && TextUtils.isEmpty(mSmsBody)) { // mms
			LogHelper.e(TAG, "updateDeatailedViewNoAtt. one");
			// subject
			remoteViews.setViewVisibility(R.id.event_sms_detailed_description,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_subject,
					mMmsSubject);
		} else if (TextUtils.isEmpty(mMmsSubject) // sms
				&& TextUtils.isEmpty(mMmsBody) && !TextUtils.isEmpty(mSmsBody)) {
			LogHelper.e(TAG, "updateDeatailedViewNoAtt. two");
			// subject
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_sms_detailed_description,
					View.VISIBLE);
			//add by gaoge for fix bug 0014249
			if(mSmsBody.equals(" ")){
				mSmsBody = mContext.getString(R.string.no_message);
			}
			remoteViews.setTextViewText(R.id.event_sms_detailed_description,
					mSmsBody);
		} else if (TextUtils.isEmpty(mMmsSubject) // sms
				&& TextUtils.isEmpty(mMmsBody) && TextUtils.isEmpty(mSmsBody)) {
			LogHelper.e(TAG, "updateDeatailedViewNoAtt. three");
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.GONE);

			if (mSMSCount == 1 || mMMSCount == 1) { // indicate unread message
				remoteViews.setViewVisibility(
						R.id.event_sms_detailed_description, View.VISIBLE);
				remoteViews.setTextViewText(
						R.id.event_sms_detailed_description,
						mContext.getString(R.string.no_message));
			} else { // indicate missedcall and voicemail
				remoteViews.setViewVisibility(
						R.id.event_sms_detailed_description, View.GONE);
			}
		}
	}

	private void updateDetailedViewSingleAtt(RemoteViews remoteViews) {
		LogHelper.d(TAG, "updateDetailedViewSingleAtt. mmsSubject: "
				+ mMmsSubject + " , mmsBody: " + mMmsBody + "attGenericCount: "
				+ mAttGenericCount);

		remoteViews.setViewVisibility(R.id.event_sms_detailed_description,
				View.GONE);

		if (mAttGenericCount != 0) {
			remoteViews.setViewVisibility(R.id.mms_attachement_icon,
					View.VISIBLE);
		} else {
			remoteViews.setViewVisibility(R.id.mms_attachement_icon, View.GONE);
		}

		// image
		if (mIsHaveMMSImage && mBitmap != null) {
			LogHelper.d(TAG, "updateDetailedViewSingleAtt. 1");
			remoteViews.setViewVisibility(R.id.contact_image_framelayout,
					View.GONE);
			remoteViews.setViewVisibility(R.id.mms_image_framelayout,
					View.VISIBLE);
			remoteViews.setImageViewBitmap(R.id.mms_detailed_image, mBitmap);
		} else {
			LogHelper.d(TAG, "updateDetailedViewSingleAtt. 2");
			remoteViews.setViewVisibility(R.id.contact_image_framelayout,
					View.VISIBLE);
			remoteViews
					.setViewVisibility(R.id.mms_image_framelayout, View.GONE);
			if (null == mBitmap) {
				remoteViews.setImageViewResource(R.id.contact_detailed_image,
						R.drawable.event_nobody);
				remoteViews.setViewVisibility(R.id.contact_vip_image,
						View.INVISIBLE);
				// TODO; If don't down mms, what should be shown?
			} else {
				remoteViews.setImageViewBitmap(R.id.contact_detailed_image,
						mBitmap);
				if (mIsVip) {
					remoteViews.setViewVisibility(R.id.contact_vip_image,
							View.VISIBLE);
				} else {
					remoteViews.setViewVisibility(R.id.contact_vip_image,
							View.INVISIBLE);
				}
			}
		}

		// body
		if (!TextUtils.isEmpty(mMmsSubject) && !TextUtils.isEmpty(mMmsBody)) {
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_subject,
					mMmsSubject);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_description,
					mMmsBody);
		} else if (TextUtils.isEmpty(mMmsSubject)
				&& !TextUtils.isEmpty(mMmsBody)) { // mms
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_description,
					mMmsBody);
		} else if (!TextUtils.isEmpty(mMmsSubject)
				&& TextUtils.isEmpty(mMmsBody)) {
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_subject,
					mMmsSubject);
		} else if (TextUtils.isEmpty(mMmsSubject)
				&& TextUtils.isEmpty(mMmsBody)) {
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_subject,
					mContext.getString(R.string.no_message));
		}
	}

	private void updateDetailedViewMultiAtt(RemoteViews remoteViews) {
		remoteViews.setViewVisibility(R.id.event_sms_detailed_description,
				View.GONE);
		remoteViews.setViewVisibility(R.id.mms_attachement_icon, View.VISIBLE);
		remoteViews.setViewVisibility(R.id.mms_image_framelayout, View.GONE);
		remoteViews.setViewVisibility(R.id.contact_image_framelayout,
				View.VISIBLE);

		if (null == mBitmap) {
			remoteViews.setImageViewResource(R.id.contact_detailed_image,
					R.drawable.event_nobody);
			remoteViews.setViewVisibility(R.id.contact_vip_image,
					View.INVISIBLE);
			// TODO; If don't down mms, what should be shown?
		} else {
			remoteViews
					.setImageViewBitmap(R.id.contact_detailed_image, mBitmap);
			if (mIsVip) {
				remoteViews.setViewVisibility(R.id.contact_vip_image,
						View.VISIBLE);
			} else {
				remoteViews.setViewVisibility(R.id.contact_vip_image,
						View.INVISIBLE);
			}
		}

		if (!TextUtils.isEmpty(mMmsSubject) && !TextUtils.isEmpty(mMmsBody)) {
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_subject,
					mMmsSubject);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_description,
					mMmsBody);
		} else if (TextUtils.isEmpty(mMmsSubject)
				&& !TextUtils.isEmpty(mMmsBody)) { // no
			// verify
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_description,
					mMmsBody);
		} else if (!TextUtils.isEmpty(mMmsSubject)
				&& TextUtils.isEmpty(mMmsBody)) {
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.VISIBLE);
			remoteViews.setTextViewText(R.id.event_mms_detailed_subject,
					mMmsSubject);
		} else if (TextUtils.isEmpty(mMmsSubject)
				&& TextUtils.isEmpty(mMmsBody)) {
			remoteViews.setViewVisibility(R.id.event_mms_detailed_description,
					View.GONE);
			remoteViews.setViewVisibility(R.id.event_mms_detailed_subject,
					View.GONE);
		}
	}
}
